#include <iostream>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <error.h>

using namespace std;


int main()
{
    int money = 10000;
    char buffer[20];
    int fd = open("./text1.txt", O_CREAT | O_WRONLY | O_TRUNC);
    if (fd < 0) 
    {
        perror("open error:");
        exit(-1);
    }

    /* 创建子进程 */
    pid_t pid = fork();

    if(pid < 0)
    {
        perror("fork error:");
        _exit(-1);
    }
    else if(pid == 0)
    {   // 子进程

        int cnt = 5;
        while(cnt--)
        {
            cout << "child process: " << getpid() << endl;
            cout << "child parent process: " << getppid() << endl;  //不加while(1)延时的话，父进程退出，子进程变为孤儿进程，又init托管，所以getppid = 1；
            sleep(1);
        }

        cout << "子进程结束执行"  << endl;

        /* 子进程退出 */
        _exit(0);
        
    }
    else //(pid > 0)
    {   //父进程返回的是子进程id
        cout << "parent process: " << getpid() << endl;
        cout << "parent pid: " << pid << endl;

        /* 阻塞回收子进程的资源 */
        wait(NULL);
        cout << "abab" << endl;
    }

    //不加延时的话，
    while(1)
    {
        sleep(1);
    }
    
    return 0;

}
